package com.zyh.flink.day06.function;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.state.KeyedStateStore;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

public class StateTest {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment environment = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<String> dataStreamSource = environment.socketTextStream("hadoop10", 9998);

        KeyedStream<Tuple2<String, Integer>, String> keyedStream = dataStreamSource.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
                String[] words = value.split("\\s+");

                for (String word : words) {
                    out.collect(Tuple2.of(word, 1));
                }
            }
        }).keyBy(t -> t.f0);

        SingleOutputStreamOperator<Tuple2<String, Integer>> result = keyedStream
                .window(TumblingProcessingTimeWindows.of(Time.seconds(5)))
                .process(new ProcessWindowFunction<Tuple2<String, Integer>, Tuple2<String, Integer>, String, TimeWindow>() {
                    private ValueStateDescriptor<Integer> wvsd;
                    private ValueStateDescriptor<Integer> gvsd;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        this.wvsd = new ValueStateDescriptor<Integer>("wsd", Types.INT);
                        this.gvsd = new ValueStateDescriptor<Integer>("gsd", Types.INT);
                    }
                    /**
                     *
                     * @param key 分组依据
                     * @param context 上下文对象，可以通过这个对象获取到元数据信息
                     * @param elements 窗口中所有元素：
                     * @param collector collector，用来把数据发送给下游
                     */
                    @Override
                    public void process(String key, Context context, Iterable<Tuple2<String, Integer>> elements, Collector<Tuple2<String, Integer>> collector) throws Exception {

                        KeyedStateStore windowStateStore = context.windowState();
                        KeyedStateStore globalStateStore = context.globalState();

                        ValueState<Integer> windowState = windowStateStore.getState(wvsd);
                        ValueState<Integer> globalState = globalStateStore.getState(gvsd);


                        int count = 0;
                        for (Tuple2<String, Integer> element : elements) {
                            count += element.f1;
                        }

                        Integer oldCount1 = windowState.value();
                        if (oldCount1 == null) {
                            oldCount1 = 0;
                        }
                        windowState.update(count + oldCount1);
                        System.out.println("oldCount1 = " + oldCount1);
                        Integer oldCount2 = globalState.value();
                        if (oldCount2 == null) {
                            oldCount2 = 0;
                        }
                        globalState.update(oldCount2 + count);
                        System.out.println("oldCount2 = " + oldCount2);
                        TimeWindow window = context.window();

                        collector.collect(Tuple2.of(key, count));
                    }
                });
        result.print();
        environment.execute("Job");
    }
}
